#include "cipher.h"
#include <openssl/des.h>
#include <QDebug>
#include <string>

#define KEY_SIZE_8B            8
#define KEY_SIZE_24B            24
#define KEY_SIZE_32B            32

CDes::CDes(QObject *parent) : CCipher(parent)
{
    ctx = EVP_CIPHER_CTX_new();
    EVP_CIPHER_CTX_init(ctx);
}

//CDes:
bool CDes::encrypt(const QByteArray &in, QByteArray &out, const QByteArray &key, bool enc, int mode)
{
    if(mode == 0) //ecb模式
    {

        int Paddingsize = KEY_SIZE_8B - key.size();
        QByteArray newkey(key);
        newkey.append(Paddingsize, 0);

        // 根据key大小创建EVP_CIPHER
        const EVP_CIPHER * cipher = nullptr;
        if (newkey.size() == KEY_SIZE_8B)
        {
            cipher = EVP_des_ecb();
        }

        // 执行加解密
        return encryption(in, out, newkey, QByteArray(), cipher, enc);
    } else if(mode == 1) //cbc模式
    {
        int Paddingsize = KEY_SIZE_8B - key.size();
        QByteArray newkey(key);
        newkey.append(Paddingsize, 0);
        Q_ASSERT(ivec.size() == KEY_SIZE_8B); // 初始向量为8字节

        // 根据key大小创建EVP_CIPHER
        const EVP_CIPHER * cipher = nullptr;
        if (newkey.size() == KEY_SIZE_8B)
        {
            cipher = EVP_des_cbc();
        }
        // 执行加解密
        return encryption(in, out, newkey, ivec, cipher, enc);
    }

    else if(mode == 2) // cfb1模式
    {
        int Paddingsize = KEY_SIZE_8B - key.size();
        QByteArray newkey(key);
        newkey.append(Paddingsize, 0);
        Q_ASSERT(ivec.size() == KEY_SIZE_8B); // 初始向量为16字节

        // 根据key大小创建EVP_CIPHER
        const EVP_CIPHER * cipher = nullptr;
        if (newkey.size() == KEY_SIZE_8B)
        {
            cipher = EVP_des_cfb1();
        }
        // 执行加解密
        return encryption(in, out, newkey, ivec, cipher, enc);
    }

    else if(mode == 3) //ofb模式
    {
        int Paddingsize = KEY_SIZE_8B - key.size();
        QByteArray newkey(key);
        newkey.append(Paddingsize, 0);
        Q_ASSERT(ivec.size() == KEY_SIZE_8B); // 初始向量为8字节

        // 根据key大小创建EVP_CIPHER
        const EVP_CIPHER * cipher = nullptr;
        if (newkey.size() == KEY_SIZE_8B)
        {
            cipher = EVP_des_ofb();
        }

        // 执行加解密
        return encryption(in, out, newkey, ivec, cipher, enc);
    }
}

bool CDes::encrypt(const QByteArray &in, QByteArray &out, const QByteArray &key, bool enc, int mode, const QByteArray &ivec)
{

}

bool CDes::encrypt(const QByteArray &in,QByteArray &out,int mode)
{
}
